package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.Contact;
import util.DBHelp;
import util.RowMapper;

public class ContactDao {

    DBHelp<Contact> dbHelp = new DBHelp<Contact>();

    public int addContact(Contact contact) {
        String sql = "insert into bmw_contact (name, company, mobile, phone, email, address, home_page, weibo, introduce, bmw_project_id) value(?,?,?,?,?,?,?,?,?,?)";
        return dbHelp.excuteSQL(sql, contact.getName(), contact.getCompany(),
                contact.getMobile(), contact.getPhone(), contact.getEmail(),
                contact.getAddress(), contact.getHomePage(),
                contact.getWeibo(), contact.getIntroduce(),
                contact.getProjectId());
    }
    
    public Contact findByName(String name) {
        String sql = "select * from bmw_contact where name = ?";
        return dbHelp.executeForObject(sql, new ContactRowMapper(), name);
    }

    public List<Contact> findByProjectId(int projectId) {
        String sql = "select * from bmw_contact where bmw_project_id = ?";
        return dbHelp.excuteForList(sql, new ContactRowMapper(), projectId);
    }

    public int delById(int id) {
        String sql = "delete from bmw_contact where id = ?";
        return dbHelp.excuteSQL(sql, id);
    }

    public Contact findByContactId(int id) {
        String sql = "select * from bmw_contact where id = ?";
        return dbHelp.executeForObject(sql, new ContactRowMapper(), id);
    }

    public int updateContact(Contact contact) {
        String sql = "update  bmw_contact set name = ?, company = ? , mobile = ? , phone = ? , email = ? , address = ?, home_page = ?, weibo = ?, introduce = ? where id =?";
        return dbHelp.excuteSQL(sql, contact.getName(), contact.getCompany(),
                contact.getMobile(), contact.getPhone(), contact.getEmail(),
                contact.getAddress(), contact.getHomePage(),
                contact.getWeibo(), contact.getIntroduce(), contact.getId());

    }

    private class ContactRowMapper implements RowMapper<Contact> {

        @Override
        public Contact mapperRow(ResultSet rs) throws SQLException {

            Contact contact = new Contact();
            contact.setId(rs.getInt("id"));
            contact.setName(rs.getString("name"));
            contact.setCompany(rs.getString("company"));
            contact.setMobile(rs.getString("mobile"));
            contact.setPhone(rs.getString("phone"));
            contact.setEmail(rs.getString("email"));
            contact.setAddress(rs.getString("address"));
            contact.setHomePage(rs.getString("home_page"));
            contact.setWeibo(rs.getString("weibo"));
            contact.setIntroduce(rs.getString("introduce"));
            contact.setProjectId(rs.getInt("bmw_project_id"));
            return contact;
        }

    }
}
